"use strict";
const Controller = require("egg").Controller;
const code = require("../errorCode.js");

class Dict extends Controller {
  async list() {
    const { ctx, app } = this;
    try {
      const conn = await this.app.mysql.get("meta");
      const dict = await conn.get("dictionary_list", {
        name: ctx.request.body.name,
      });
      if (dict) {
        let params = { ...ctx.request.body };
        delete params.name;
        params.dictionary_id = dict.id;
        const rows = await conn.query(
          `select value,label${
            dict.mapper || ""
          } from dictionary_info ${ctx.whereStr(params)}`
        );
        ctx.body = app.done({ rows });
      } else {
        ctx.body = app.error(
          code.DICT_NO_NAME,
          `该字典[${ctx.request.body.name}]没有被定义，请联系管理员！`
        );
      }
    } catch (e) {
      ctx.body = app.error(code.DICT_ERR, "获取字典时发生错误" + e);
    }
  }

  async organ(){
    const {ctx,service} = this
    const rows = await service.mysql.tree('meta','organ','value',ctx.request.body)
    ctx.body = rows
  }

  async organList(){
    const {ctx,service} = this
    const rows = await service.mysql.find('meta','organ','value',ctx.request.body,[],0,99)
    ctx.body = rows
  }

  async tree() {
    const { ctx, app } = this;
    try {
      const conn = await this.app.mysql.get("meta");
      const dict = await conn.get("dictionary_list", {
        name: ctx.request.body.name,
      });

      if (dict) {
        let params = { ...ctx.request.body };
        delete params.name;
        params.dictionary_id = dict.id;
        const rows = await conn.query(
          `select value,label,parent${
            dict.mapper || ""
          } from dictionary_info ${ctx.whereStr(params)} and parent is null`
        );
        if (Array.isArray(rows)) {
          let tree = [];
          for (let i = 0; i < rows.length; i++) {
            let where = { ...ctx.request.body };
            delete where.name;
            delete where["value"];
            delete where["parent"];
            where.dictionary_id = dict.id;
            tree.push(
              await this.getChildren(conn, dict.mapper, rows[i], where)
            );
          }
          ctx.body = app.done({ tree });
        } else {
          ctx.body = app.error(
            code.TREE_NOT_ARRAY,
            "树的返回结果不是数组！" + JSON.stringify(rows)
          );
        }
      } else {
        ctx.body = app.error(
          code.DICT_NO_NAME,
          `该字典[${ctx.request.body.name}]没有被定义，请联系管理员！`
        );
      }
    } catch (e) {
      ctx.body = app.error(code.DICT_ERR, "获取字典时发生错误" + e);
    }
  }

  async getChildren(conn, mapper, row, where) {
    const { ctx } = this;
    const rows = await conn.query(
      `select value,label,parent${mapper || ""} from dictionary_info ${ctx.whereStr(where)} and parent=${row.value}`
    );
    if (Array.isArray(rows)) {
      if (rows.length > 0) {
        let child = [];
        for (let i = 0; i < rows.length; i++) {
          child.push(await this.getChildren(conn, mapper, rows[i], where));
        }
        return { ...row, children: child };
      } else {
        return row;
      }
    }
    {
      return row;
    }
  }
}

module.exports = Dict;
